#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

. $CCI_SRC/container/defconfig.sh

docker_rm dnsmasq

kill $(ps -ef| grep dnsmasq| grep libvirt| awk '{print $2}') 2> /dev/null

WORKSPACE=$(dirname "$(realpath "$0")")
DNSMASQ_CONF_DIR="/etc/compass-ci/dnsmasq"

# config custom br0
[ -n "$br0_segment" ] && sed -i "/dhcp-range=/{ s/172.18/${br0_segment}/g }" dnsmasq.d/dnsmasq.conf

# load custom dnsmasq.conf
[ -d "${DNSMASQ_CONF_DIR}/dnsmasq.d/" ] &&
	cp -a ${DNSMASQ_CONF_DIR}/dnsmasq.d/* ${WORKSPACE}/dnsmasq.d/

# persist the dhcp lease file
[ -d "${DNSMASQ_CONF_DIR}/lease_dir" ] ||
	mkdir -p ${DNSMASQ_CONF_DIR}/lease_dir

cmd=(
	docker run
	--restart=always
	--cap-add NET_ADMIN
	--net=host
	--publish 67:67/udp
	--publish 69:69/udp
	-v ${WORKSPACE}/dnsmasq.d:/etc/dnsmasq.d
	-v ${WORKSPACE}/conf/etc/resolv.conf:/etc/resolv.conf:ro # specify the upstream dns server of dnsmasq
	-v ${DNSMASQ_CONF_DIR}/lease_dir:/var/lib/misc # persist the dhcp lease file
	-v /etc/localtime:/etc/localtime:ro
	-v /tftpboot:/tftpboot:ro
	--detach
	--name dnsmasq
	dnsmasq:alpine
	dnsmasq -k
)

"${cmd[@]}"
